package no.saiboten.milkywave.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.springframework.stereotype.Component;

@Component
public class MilkyWaveHttpService {

	SimpleDateFormat sdf;

	public MilkyWaveHttpService() {
		sdf = new SimpleDateFormat("ddMMyyyy/kkmm");
	}

	public double findValue() {

		try {
			URL url = new URL(
					"http://www2.nve.no/h/hd/plotreal/Q/0062.00015.000/basis.txt");
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					url.openStream()));
			String line;

			while ((line = reader.readLine()) != null) {
				String[] lineInPieces = line.trim().split("\\s+");
				if (lineInPieces.length > 0) {
					if (findWaterLevelFromDate(lineInPieces[0])) {
						System.out.println(line);
						return Double.parseDouble(lineInPieces[2]);
					}
				}
			}
			reader.close();

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return -1;
	}

	public double findLatestValue() {
		Double latestResult = -1.0;
		try {
			URL url = new URL(
					"http://www2.nve.no/h/hd/plotreal/Q/0062.00015.000/basis.txt");
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					url.openStream()));
			String line;

			while ((line = reader.readLine()) != null) {
				String[] lineInPieces = line.trim().split("\\s+");
				if (lineInPieces.length > 1) {
					try {
						latestResult = Double.parseDouble(lineInPieces[2]);
					} catch (Exception u) {
						System.out.println(u.getMessage());
					}
				}
			}
			reader.close();

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return latestResult;
	}

	private boolean findWaterLevelFromDate(String string) {

		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.HOUR_OF_DAY, 9);

		Calendar cal2 = Calendar.getInstance();

		try {
			Date tryThisDate = sdf.parse(string);

			cal2.setTime(tryThisDate);

			if (cal.get(Calendar.DAY_OF_MONTH) == cal2
					.get(Calendar.DAY_OF_MONTH)
					&& cal.get(Calendar.YEAR) == cal2.get(Calendar.YEAR)
					&& cal.get(Calendar.MONTH) == cal2.get(Calendar.MONTH)
					&& cal.get(Calendar.HOUR_OF_DAY) == cal2
							.get(Calendar.HOUR_OF_DAY)) {
				System.out.println("Found the right time! It is: "
						+ tryThisDate);
				return true;
			}

		} catch (Exception u) {
			System.out.println("Couldn't parse date: " + u);
		}
		return false;
	}
}
